package com.theaf.core.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 包工具类.
 * @author huangligui
 * @date 2015-11-20
 *
 */
public class ZipHelper {

    public static void unPack(String zipPath,String destPath)
    {
    	try {
			unPack(new FileInputStream(zipPath),destPath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
          
    }
    
    
    public static void unPack(byte bs[],String destPath)
    {
    	 unPack(new ByteArrayInputStream(bs), destPath);
    }
    
    public static void unPack(InputStream in,String destPath)
    {
    	File f = null;
    	 try {
             ZipInputStream zin  = new ZipInputStream(in);
             byte bs[];
             ZipEntry e;
             while( (e = zin.getNextEntry()) != null )
             {
                 bs = new byte[1024];

                 f = new File(destPath +  File.separator + e.getName().replaceAll("\\\\",File.separator));
                 if( !f.exists() )
                 {
                     if(e.isDirectory()){
                     	f.mkdir();
                     	continue;
                     }  
                     else
                     {
                     	 f.getParentFile().mkdirs();
                     	 f.createNewFile();
                     }
                 }
                 else
                 {
                     if(e.isDirectory()){
                         continue;
                     }
                 }
                 FileOutputStream out = new FileOutputStream(f);
                 int count = -1;
                 while( (count=zin.read(bs)) != -1 )
                 {
                     out.write(bs,0,count);
                 }
                 out.flush();
                 out.close();
             }
             zin.closeEntry();
         }catch (IOException e) {
             e.printStackTrace();
         }
    }
}
